package com.fourGirlsAndADude.mobileDRT;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;

import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.Menu;
import com.att.intern.webservice.Incident;
import com.att.intern.webservice.Webservice;
import com.att.intern.webservice.Webservice.TokenInvalidException;

//http://stackoverflow.com/questions/15264769/horizontal-progress-bar-does-not-update-its-status
public class SearchableActivity extends SherlockListActivity {
	private Webservice webservice = LoginActivity.webService;
	private String searchQuery;
	private ArrayList<Incident> incidents;
	private ArrayList<BuildingInfo> infos;
	private String token;
	private String sQuery;
	private String tag = "SearchableActivity";
	private TextView displayMessage;
	private ProgressBar progess;
	private ListView list;
	boolean isIncident;
	private int query;
	private String user;
	private String authType;
	private String picture;
	private TextView empty;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.v(tag, "In on create");
		setContentView(R.layout.activity_searchable);
		// handleIntent(getIntent());
		Intent intent = getIntent();
		token = intent.getStringExtra("SESSION_TOKEN");
		user = intent.getStringExtra("USERNAME");
		authType = intent.getStringExtra("AUTHORIZATION_TYPE");
		picture = this.getIntent().getStringExtra("PictureFile");
		System.out.println("Picture path: "+picture);
		progess = (ProgressBar) findViewById(R.id.pBar);
		list = (ListView) findViewById(android.R.id.list);
		empty = (TextView) findViewById(android.R.id.empty);
		empty.setVisibility(View.GONE);
		//Log.v(tag, token);
		// Get the intent, verify the action and get the query
		handleIntent(intent);
	}

	private void handleIntent(Intent intent) {
		// TODO Auto-generated method stub
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			sQuery = intent.getStringExtra(SearchManager.QUERY);
			Log.v(tag, sQuery);
			SearchQuery searchQuery = new SearchQuery();
			searchQuery.execute((Void) null);
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-geneeratemethod stub
		super.onNewIntent(intent);
		Log.v(tag, "passing intent");
		setIntent(intent);
		handleIntent(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getSupportMenuInflater().inflate(R.menu.searchable, menu);
		// associating the searchable configuration with the search service...
		// http://stackoverflow.com/questions/13267384/actionbarsherlock-searchview-cast-error
		// http://stackoverflow.com/questions/14991980/actionbarsherlock-searchview-setonquerytextlistener
		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		com.actionbarsherlock.widget.SearchView searchView = (com.actionbarsherlock.widget.SearchView) menu
				.findItem(R.id.menu_search).getActionView();
		searchView.setSearchableInfo(searchManager
				.getSearchableInfo(getComponentName()));
		return true;
	}

	private class SearchQuery extends AsyncTask<Void, Void, Boolean> {
		private ArrayList<Incident> locs = new ArrayList<Incident>();
		private ArrayList<BuildingInfo> infos = new ArrayList<BuildingInfo>();
		private Hashtable<Integer, String> glcInfo;
		private BuildingInfo info;
		private boolean found;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			query = Integer.parseInt(sQuery);
			progess.setIndeterminate(true);
			progess.setVisibility(android.view.View.VISIBLE);
			Log.v(tag, "Grabbing info from hash");
			// Get hashtable from webservice
			glcInfo = LoginActivity.webService.getGLCInfo();
			// Grab glcs from hashtable
			Log.v(tag, "Grabbing keys");
			Enumeration<Integer> glckeys = glcInfo.keys();
			// Cycle through glcs until a match is found;
			Log.v(tag, "looking for match");
			while (glckeys.hasMoreElements()) {
				Integer element = (Integer) glckeys.nextElement();
				if (query == element) {
					Log.v(tag, "found");
					found = true;
					break;
				}
			}

		}

		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if (found) {
				try {
					locs = webservice.geolocSearch(token, query);
					if (locs.size() == 0) {
						String value = glcInfo.get(query);
						String[] values = value.split("~");
						info = new BuildingInfo(values[0], values[1],
								values[2], values[3]);
						infos.add(info);
						isIncident = false;
					} else {
						isIncident = true;
					}
					return true;
				} catch (TokenInvalidException e) {
					return null;
				}
			}

			return false;
		}

		@Override
		protected void onPostExecute(Boolean success) {
			// TODO Auto-generated method stub
			super.onPostExecute(success);

			BuildingInfoAdapter adapter;

			if (success) {
				Log.v(tag, "Successful");
				if (locs.size() == 0 || locs == null) {
					Log.v(tag, "closed");
					SearchableActivity.this.infos = infos;
					adapter = new BuildingInfoAdapter(infos, getBaseContext());
					setListAdapter(adapter);
					adapter.notifyDataSetChanged();

				} else {
					Log.v(tag, "open");
					incidents = locs;
					adapter = new BuildingInfoAdapter(getBaseContext(),
							incidents);
					setListAdapter(adapter);
					adapter.notifyDataSetChanged();
				}
				list.setOnItemClickListener(new Listener());
				progess.setVisibility(android.view.View.GONE);

			} else if (!success) {
				progess.setVisibility(android.view.View.GONE);
				if (incidents == null) {
					empty.setText("No Incidents Found");
				} else if (!found) {
					empty.setText("Geolocation Does Not Exist");
				}
				empty.setVisibility(View.VISIBLE);
			} else {
				// Does not account for null case where the query was not found
				progess.setVisibility(android.view.View.GONE);
				Intent intent = new Intent(getBaseContext(),
						LoginActivity.class);
				intent.putExtra("LOGGED_OUT", true);
				finish();
			}
		}
	}

	private class Listener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			Log.v(tag, "Boolean: " + isIncident);
			if (isIncident) {
				displayBuildingInfo(incidents.get(arg2));
			} else {
				displayBuildingInfo(infos.get(arg2));
			}
		}
	}

	private void displayBuildingInfo(final Incident incident) {
		AlertDialog.Builder display = new AlertDialog.Builder(
				SearchableActivity.this);
		Log.v("DialogBox", "Attempting to create dialog");
		String recNum = "Record Number: " + incident.getRecNumber(), glc = "GLC: "
				+ incident.getGeoLoc(), eventName = "Event Name: "
				+ incident.getEventName(), status = "Status: "
				+ incident.getIncidentStatus(), workRecNum = "Work Record Number: "
				+ incident.getWorkReqNumber();
		String[] items = { recNum, glc, eventName, status, workRecNum };
		display.setTitle(incident.getBuildingName())
				.setItems(items, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						// do nothing here
					}// End of onClick
				}// End of OnClickListner
				)// End Of setItems
					// Update Button, Launches new activity and then
					// closes dialog
				.setPositiveButton("Update",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								Intent i = new Intent(getBaseContext(),
										UpdateActivity.class);
								/*
								 * i.setClassName( this, "UpdateActivity");
								 */
								i.putExtra("SESSION", token);
								i.putExtra("USER", user);
								i.putExtra("AUTHTYPE", authType);
								i.putExtra("INCIDENT", incident);
								i.putExtra("PictureFile", picture);
								Log.d("GLCResultOpen", "Got the incident!");
								i.putExtra("RECORDID", incident.getRecNumber());
								Log.d("GLCResultOpen", "Record Number: "
										+ incident.getRecNumber());
								startActivity(i);
								dialog.cancel();
							}// End of onClick
						})// End of Set positive Button
							// Exit Button, closes dialog Box
				.setNegativeButton("Exit",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) { //
								// TODO Auto-generated method stub
								// DisplayedInfoDialog.this.getDialog().cancel();
								// } });
							}// End of onClick
						}// End of onClicklistner
				);// End of setNegative button and creation of
					// alertDialog

		Log.v("DialogBox", "Attempting to display");
		// Show Dialog box
		AlertDialog displayInfo = display.create();
		displayInfo.show();
	}

	private void displayBuildingInfo(final BuildingInfo info) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(
				SearchableActivity.this);
		// display Title
		Log.d("NoResult ", "displaying title");
		String address = "Address: " + info.getAddress(), state = "State: "
				+ info.getState(), pm = "PM: " + info.getPm();
		String[] buildingInfo = { address, state, pm };
		dialog.setTitle(info.getBuildingName())
				.setItems(buildingInfo, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

					}// End of onClick for
						// DialogInterface.OnClickListener
				})
				// End of onClickListener
				.setNegativeButton("Exit",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.cancel();
							}// End of onClick
						})// End of OnClickListener for negative button
				.setPositiveButton("Add",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

								Intent i = new Intent(getBaseContext(),
										AddActivity.class);
								i.putExtra("GLC", query);
								i.putExtra("STATE", info.getState());
								i.putExtra("PM", info.getPm());
								i.putExtra("BUILDINGNAME",
										info.getBuildingName());
								i.putExtra("ADDRESS", info.getAddress());
								i.putExtra("USER", user);
								i.putExtra("SESSION", token);
								i.putExtra("AUTHTYPE", authType);
								startActivity(i);
								dialog.cancel();

							}// End Of onClick
						});// End Of onClickListener
		Log.d("NoResult ", "Created title, list,and buttons");
		// Display Dialog Box
		Log.d("NoResult ", "Creating box");
		AlertDialog displayInfo = dialog.create();
		displayInfo.show();
	}
}